package cn.his.medical.phismange.app.Exception

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import cn.his.medical.phismange.app.App
import java.io.ByteArrayOutputStream
import java.io.PrintStream

/**
 * 作者：xiewei on 2018/3/15 14:27
 * 邮箱：xiewei19910115@163.com
 */
class ExceptionActivity : AppCompatActivity(){
    //lateinit  用于只能生命周期流程中进行获取或者初始化的变量
    private lateinit var exceptionText : TextView
    //和java代码的static意思相近
    companion object {
        private val tag : String = ExceptionActivity::class.java.simpleName;
        fun showException(throwable :Throwable){
        //初始化App
            val app : App? = App.getInstance()
            if (app != null && App.getIsDebug()){
                val byteArrayOutputStream = ByteArrayOutputStream()
                throwable.printStackTrace(PrintStream(byteArrayOutputStream))
                val msg = String(byteArrayOutputStream.toByteArray());
                try {
                    val intent = Intent(app,ExceptionActivity::class.java)
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
                    intent.putExtra("msg",msg)
                    app.startActivity(intent)
                }catch (e:Exception){
                    throw IllegalArgumentException("异常捕获未在manifest中声明")
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val scrollView = ScrollView(this)
        val linearLayout = LinearLayout(this)
        linearLayout.orientation = LinearLayout.VERTICAL
        scrollView.addView(linearLayout)
        setContentView(scrollView)
        exceptionText = TextView(this);
        linearLayout.addView(exceptionText)
        exceptionText.setTextColor(Color.RED)
        handlerIntent(intent,false)

    }

    private fun handlerIntent(intent: Intent?, b: Boolean) {
        val  msg : String? = intent!!.getStringExtra("msg") ?: return
        if (b){
            exceptionText.append("\n\n\n\n\n\n")
        }
        exceptionText.append(msg)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        handlerIntent(intent,true)
    }
}